package com.fire.web.modules.all.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fire.web.modules.all.constant.ErrorCodeConstants;
import com.fire.web.modules.all.entity.AjaxResult;
import com.fire.web.modules.all.entity.AssetCategoryModel;
import com.fire.web.modules.all.entity.FireProprietorModel;
import com.fire.web.modules.all.entity.SiteModel;
import com.fire.web.modules.all.service.IAssetCategoryService;
import com.fire.web.modules.all.service.IAssetService;
import com.fire.web.modules.all.service.IFireProprietorService;
import com.fire.web.modules.all.service.ISiteService;
import com.fire.web.modules.all.utils.TokenUtil;
import com.fire.web.modules.all.validation.AssetDTO;
import com.fire.web.modules.sso.service.IOAuthService;
import com.fire.web.security.shiro.realm.UserRealm;
import com.smartthing.rest.model.asset.LocationAsset;
import com.smartthing.rest.model.search.AssetSearchResults;
import com.smartthing.spi.SmartThingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/asset")
public class AssetController {
	private static final Logger LOGGER = LoggerFactory.getLogger(AssetController.class);

	@Autowired
	private IAssetService assetService;

	@Autowired
	private IAssetCategoryService categoryService;

	@Autowired
	private IOAuthService oAuthService;

	@Autowired
	private IFireProprietorService fireProprietorService;

	@Autowired
	private ISiteService siteService;

	/**
	 * 查询消防资产链表(未绑定)
	 *
	 * @return
	 * @author raoyuxing
	 */
	@PostMapping(value = "/assetlist")
	@ResponseBody
	public AjaxResult assetlist(@Validated AssetDTO assetDTO, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			for (FieldError fieldError : bindingResult.getFieldErrors()) {
                LOGGER.error(fieldError.getDefaultMessage());
			}
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数错误", "参数错误");
		}
		Map<String, Object> map = new HashMap<>();
		try {
			AssetSearchResults assetlists = assetService.getAssetList(assetDTO);
			map.put("assetlists", assetlists.getResults());
			map.put("total",assetlists.getNumResults());
		} catch (SmartThingException e) {
			e.printStackTrace();
            return new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统错误", "系统错误");
		}
		return new AjaxResult(ErrorCodeConstants.SUCCESS, "成功", map, "成功");
	}


	/**
	 * 查询消防资产链表(未绑定)
	 *
	 * @return
	 * @author raoyuxing
	 */
	@PostMapping(value = "/searcassetlist")
	@ResponseBody
	public AjaxResult SearcAssetList(@Validated AssetDTO assetDTO, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			for (FieldError fieldError : bindingResult.getFieldErrors()) {
				LOGGER.error(fieldError.getDefaultMessage());
			}
			return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数错误", "参数错误");
		}
		Map<String, Object> map = new HashMap<>();
		try {
			AssetSearchResults assetlists = assetService.getSearchAssetList(assetDTO);
			map.put("assetlists", assetlists.getResults());
			map.put("total",assetlists.getNumResults());
		} catch (SmartThingException e) {
			e.printStackTrace();
			return new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统错误", "系统错误");
		}
		return new AjaxResult(ErrorCodeConstants.SUCCESS, "成功", map, "成功");
	}
	/**
	 * 查询消防资产链表(已绑定)
	 *
	 * @return
	 * @author raoyuxing
	 */
	@PostMapping(value = "/assignmentlist")
	@ResponseBody
	public AjaxResult AssignmentList(@Validated AssetDTO assetDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                LOGGER.error(fieldError.getDefaultMessage());
            }
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数错误", "参数错误");
        }
		Map<String, Object> map = new HashMap<>();
		try {
			map = assetService.getAssetListBySiteId(assetDTO);
		} catch (SmartThingException e) {
			e.printStackTrace();
            return new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统错误", "系统错误");
		}
		return new AjaxResult(ErrorCodeConstants.SUCCESS, "成功", map, "成功");
	}


	/**
	 * 查询消防资产详情
	 *
	 * @return
	 * @author raoyuxing
	 */
	@PostMapping(value = "/assetdetails")
	@ResponseBody
	public AjaxResult assetdetails(@Validated  AssetDTO assetDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                LOGGER.error(fieldError.getDefaultMessage());
            }
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数错误", "参数错误");
        }
		try {
			LocationAsset result = assetService.getAssetDetail(assetDTO);
			return new AjaxResult(ErrorCodeConstants.SUCCESS, "成功", result, "成功");
		} catch (SmartThingException e) {
			e.printStackTrace();
            return new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统错误", "系统错误");
		}
	}

	/**
	 * 查询所有资产品类
	 *
	 * @return
	 * @author raoyuxing
	 */
	@PostMapping(value = "/assetcategory")
	@ResponseBody
	public AjaxResult assetcategory(@Validated  AssetDTO monitorDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                LOGGER.error(fieldError.getDefaultMessage());
            }
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数错误", "参数错误");
        }

//		Page<AssetCategoryModel> page = new Page(monitorDTO.getPage(),monitorDTO.getPagesize());
		Wrapper<AssetCategoryModel> wrapper = new EntityWrapper<>();
		List<AssetCategoryModel> assetCategorys = categoryService.selectList(wrapper);
		Map<String, Object> map = new HashMap<>();
		map.put("assetcategorylist", assetCategorys);

		return new AjaxResult(ErrorCodeConstants.SUCCESS, "成功", map, "成功");
	}

	/**
	 * 增加资产接口
	 *
	 * @return
	 * @author raoyuxing
	 */
	@PostMapping(value = "/addasset")
	@ResponseBody
	public AjaxResult addasset(@Validated  AssetDTO assetDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                LOGGER.error(fieldError.getDefaultMessage());
            }
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数错误", "参数错误");
        }
		try {
			LocationAsset result = assetService.addAsset(assetDTO);
			return new AjaxResult(ErrorCodeConstants.SUCCESS, "成功", result, "成功");
		} catch (SmartThingException e) {
			e.printStackTrace();
            return new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统错误", "系统错误");
		}

	}

    /**
     * 删除资产接口
     *
     * @return
     * @author raoyuxing
     */
    @PostMapping(value = "/deleteasset")
    @ResponseBody
    public AjaxResult deleteasset(@Validated  AssetDTO assetDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                LOGGER.error(fieldError.getDefaultMessage());
            }
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数错误", "参数错误");
        }
        try {
            AssetSearchResults result = assetService.deleteAsset(assetDTO);
            return new AjaxResult(ErrorCodeConstants.SUCCESS, "成功", result, "成功");
        } catch (SmartThingException e) {
            e.printStackTrace();
            return new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统错误", "系统错误");
        }

    }


    /**
     * 修改资产接口
     *
     * @return
     * @author raoyuxing
     */
    @PostMapping(value = "/updateasset")
    @ResponseBody
    public AjaxResult updateasset(@Validated  AssetDTO assetDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                LOGGER.error(fieldError.getDefaultMessage());
            }
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数错误", "参数错误");
        }
        try {
            LocationAsset result = assetService.updateAsset(assetDTO);
            return new AjaxResult(ErrorCodeConstants.SUCCESS, "成功", result, "成功");
        } catch (SmartThingException e) {
            e.printStackTrace();
            return new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统错误", "系统错误");
        }
    }


	/**
	 * 消防设施链表（未绑定）
	 *
	 * @return
	 * @author raoyuxing
	 */
	@PostMapping(value = "/facilitieslist")
	@ResponseBody
	public AjaxResult facilitiesList(@Validated AssetDTO assetDTO, BindingResult bindingResult,
									 HttpServletRequest request, HttpServletResponse response) {
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                LOGGER.error(fieldError.getDefaultMessage());
            }
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数错误", "参数错误");
        }
		Map<String, Object> map = new HashMap<>();
		try {
			String siteid = getSiteIdByToken(request,response);
			assetDTO.setSiteid(siteid);
			AssetSearchResults assetlists = assetService.facilitiesList(assetDTO);
			map.put("assetlists", assetlists.getResults());
			map.put("total",assetlists.getNumResults());
			return new AjaxResult(ErrorCodeConstants.SUCCESS, "成功", map, "成功");
		} catch (SmartThingException e) {
			e.printStackTrace();
            return new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统错误", "系统错误");
		}

	}



	/**
	 * 消防设施链表(已绑定)
	 *
	 * @return
	 * @author raoyuxing
	 */
	@PostMapping(value = "/bindfacillist")
	@ResponseBody
	public AjaxResult bindFacilitiesList(@Validated({AssetDTO.BindFacilities.class}) AssetDTO assetDTO, BindingResult bindingResult,
										 HttpServletRequest request, HttpServletResponse response) {
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                LOGGER.error(fieldError.getDefaultMessage());
            }
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数错误", "参数错误");
        }
		Map<String, Object> map = new HashMap<>();
		try {
			String siteid = getSiteIdByToken(request,response);
			assetDTO.setSiteid(siteid);
			map = assetService.bindFacilitiesList(assetDTO);
		} catch (SmartThingException e) {
			e.printStackTrace();
            return new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统错误", "系统错误");
		}
		return new AjaxResult(ErrorCodeConstants.SUCCESS, "成功", map, "成功");
	}

	/**
	 * 功能描述: 根据token获取siteid
	 * @param: request response
	 * @return: siteid
	 * @auther: raoyuxing
	 * @date: 2019/2/22 14:54
	 */
	private String getSiteIdByToken(HttpServletRequest request, HttpServletResponse response){

		String token = TokenUtil.getToken(request, response);
		UserRealm.Principal principalByAccessToken = oAuthService.getPrincipalByAccessToken(token);
		String id = principalByAccessToken.getId();

		EntityWrapper<FireProprietorModel> proprietorWrapper = new EntityWrapper<>();
		proprietorWrapper.eq("adminid",id);
		FireProprietorModel proprietor = fireProprietorService.selectOne(proprietorWrapper);

		EntityWrapper<SiteModel> siteWrapper = new EntityWrapper<>();
		siteWrapper.eq("proprietor",proprietor.getProprietor());
		SiteModel site = siteService.selectOne(siteWrapper);

		return site.getSiteid();
	}
}
